const tool = require('./tool.js');
//手动合成时间秒
var manualHbTime = 5
//买猫最长时间
var buyCatTime = 20
//广告页面的关键字
var videoKeys = ['观看完整', '完整视频', '反馈', '跳过', '点击图标', '扭动手机', '任务已完成', '秒后发放', '立即体验', '立即下载', '获得现金', '了解更多', '可领取奖励', '点击安装']
//进入广告弹窗的关键字
var enterVideoDialog = ['得大量爱心', '加速修复', '驱逐年兽', '可获得大量奖励', '离开的这段时间', '小青蛙的礼物', '免费领取', '所有猫猫凑齐的爱心', '持续时间', '收养它吧', '立即收养', '收养小猫', '欢迎回来']
//允许关闭的弹窗关键字
var hasOpenCloseDialog = ['继续升级', '确定', '开心收下', '禁止', '取消', '当前猫舍等级', '放弃福利', '跳过', '拒绝', '返回']
//退出脚本的关键字
var exitKeys = ['防沉迷提示', '明日再来', '注意休息', '达到上限', '观看广告次数']
//主页面的关键字
var home = ['猫', '收养', '财神猫', '体现', '养猫', '流浪猫', '猫宝', '猫咪']
//主页弹窗关键字
var closeHomeKeys = ['财神猫计划', '现金体现', '当前余额', '合成财猫','我的进度','连续打卡','每看一个广告','我的永久财神猫']

//当前界面未变化的次数
var notChangeCount = 0
//不在主页面的次数
var notHomeCount = 0
//界面未变化的最大次数
var maxNotChangeCount = 5

function main(params) {
    if (params && params.videoKeys) {
        videoKeys = videoKeys.concat(params.videoKeys.split(','))
    }
    if (params && params.enterVideoDialog) {
        enterVideoDialog = enterVideoDialog.concat(params.enterVideoDialog.split(','))
    }
    if (params && params.hasOpenCloseDialog) 
    {
        hasOpenCloseDialog = hasOpenCloseDialog.concat(params.hasOpenCloseDialog.split(','))
    }
    launchApp('幸福庄园')
    while (true) {
        //截取当前屏幕
        captureScreen(`./image/dqpm.png`);
        buyCat()
        hb()
        checkRestartApp()
    }
}


//买猫
function buyCat() {
    let startTime = new Date().getTime()
    while (true) {
        let hbTime = new Date().getTime() - startTime
        if (hbTime / 1000 > buyCatTime) {
            tool.log(`购买时间超过${buyCatTime}秒,结束`)
            break
        }
        let d = atWhen()
        if (d === 0) {   //不在主页
            launchApp('幸福庄园')
            break
        } else if (d === 1) {    //进入看视频买爱心
            waitAD()   //等待广告时间结束
        } else if (d === 2) {    //场地已满
            break
        } else if (d === 3) {   //正常 买猫
            click(device.width / 2, device.height - 100)
        } else if (d === 4 || d === 5) {    //在广告页面
            waitAD()   //等待广告时间结束
        } else {
            break
            // tool.log('购买时,其他状态' + d)
        }
    }
    tool.log("购买结束")
}


//合成猫咪
function hb() {
    let startTime = new Date().getTime()
    while (true) {
        if ((new Date().getTime() - startTime) / 1000 > manualHbTime) {
            break
        }
        let d = atWhen()
        //0:未知状态,1:领爱心,2:场地已满,3:在主页,正常,4:正在播放广告,5:需要进入播放广告的弹窗,6:其他弹窗,7:采集道具,8:不能关闭的弹窗
        if (d === 0) {
            launchApp('幸福庄园')
            break
        } else if (d === 3 || d === 2) {
            let roomCat = lookCat()
            swipe(roomCat.x1, roomCat.y1, device.width / 2, device.height / 2, 200)
        } else if (d === 4 || d === 5) {    //在广告页面
            waitAD()   //等待广告时间结束
        } else {
            break
            // tool.log('合成时,其他状态' + d)
        }
    }
    tool.log('合成结束')
}



//当前页面处于什么状态
//0:未知状态,1:领爱心,2:场地已满,3:在主页,正常,4:正在播放广告,5:需要进入播放广告的弹窗,6:其他弹窗,7:采集道具,8:不能关闭的弹窗
function atWhen() {
    let d = 0
    let f = 0
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)
    for (let i = 0; i < res.length; i++) {
        let t2 = res[i].text
        // tool.log(`识别到文本${t2}`)
        if (t2.includes('领爱心')) {
            d = 1
            tool.log(`进入video`)
            click(res[i]['bounds'].centerX(), res[i]['bounds'].centerY())
            sleep(2000)
            break
        }
        if (t2.includes('场地已满')) {
            d = 2
            break
        }
        if (t2.includes('猫')) {
            f = f + 1
        } else if (t2.includes('提现')) {
            f = f + 1
        }


        //退出脚本关键字
        for (let j = 0; j < exitKeys.length; j++) {
            let t = exitKeys[j]
            if (t2.includes(t)) {
                tool.log(`发现脚本关键字`)
                exit()
            }
        }

        //其他弹窗,关闭即可
        for (let j = 0; j < hasOpenCloseDialog.length; j++) {
            let t = hasOpenCloseDialog[j]
            if (t2.includes(t)) {
                tool.log(`发现可允许关闭的弹窗${t}`, 'debug')
                d = 6
                if (t === '当前猫舍等级') {
                    click(device.width / 2, device.height / 3 * 2)
                } else {
                    tool.clickhasTextByScreenCapture(t)
                    closePop2()    //关闭弹窗
                }
                break
            }
        }

        //其他弹窗,关闭即可，定位坐标
        for (let j = 0; j < closeHomeKeys.length; j++) {
            let t = closeHomeKeys[j]
            if (t2.includes(t)) {
                tool.log(`发现可允许关闭的弹窗2`, 'debug')
                d = 6
                if( t === '合成财猫' || t === '每日打卡'|| t === '连续打卡'|| t === '我的进度'   ){
                    click(device.width * 0.93, device.height * 0.22)
                }else{
                    click(device.width * 0.93, device.height * 0.18)
                }
               
                break
            }
        }


        //进入广告的弹窗
        for (let j = 0; j < enterVideoDialog.length; j++) {
            let t = enterVideoDialog[j]
            if (t2.includes(t)) {
                tool.log(`发现进入video的弹窗关键字`, 'debug')
                click(device.width / 2, device.height / 40 * 25)
                d = 5
                sleep(300)
                break
            }
        }

        //广告页面
        if (text('反馈').exists() && text('反馈').findOne(2000).bounds().bottom < 300) {
            console.log(text('反馈').findOne(2000).bounds())
            d = 4
            break
        }
        for (let j = 0; j < videoKeys.length; j++) {
            let t = videoKeys[j]
            if (t2.includes(t)) {
                tool.log(`正在video页面,存在`, 'debug')
                d = 4
                break
            }
        }

        if (t2 === '自动') {
            d = 7
            tool.clickTextByScreenCapture('自动')
            break
        }

        if (d !== 0) {
            break
        }

    }
    if (d === 0 && f >= 2) {
        d = 3
    }
    if (d === 3) {
        //主页是否有广告
        if (tool.hasText('点击广告')) {
            d = 8
            tool.log(`不能关闭的弹窗`)
            restartApp()
        }
    }

    if (d === 0) {
        notHomeCount++
    } else {
        notHomeCount = 0
    }
    // tool.log(`当前状态:${d}`, 'debug')
    return d;
}


//等待广告时间结束
function waitAD() {
    //广告是否播放完毕
    let playOver = false
    let startTime = new Date().getTime()
    while (true) {
        captureScreen(`./image/dqpm.png`);
        //观看广告时间
        let watchTime = new Date().getTime() - startTime
        if (watchTime > 1000 * 60) {
            tool.log('video播放超时')
            break
        } else {
            tool.log(`video播放时间:${watchTime / 1000}s`)
        }

        if (checkRunPage()) {    //在主页
            playOver = true
            tool.log('当前在主页')
            break
        }
        if (atAdvice()) { //在广告页面
            notHomeCount = 0
            if (hasPlayOver()) {     //播放完毕
                closeAD() //关闭广告
                break
            } else { //正在播放
                closePlayAdviceDialog()   //关闭广告播放中的弹窗
            }
        } else {   //未知页面
            tool.log('未知页面')
            launchApp('幸福庄园')
        }

    }
    return playOver;
}


//判断界面是否有变化
function isChange() {
    let p = null;
    let option = {
        "region": [0, 0, device.width, device.height],
        "threshold": 0.95
    }
    p = tool.findImage("dqpm.png", option)
    if (p) {
        notChangeCount++
        tool.log(`界面未变化${notChangeCount}`)
        return false
    } else {
        notChangeCount = 0
        // console.log(`界面变化`)
        return true
    }
}


//寻找一个猫咪
function lookCat() {
    let x1 = random(100, device.width - 100)
    let y1 = random(device.height / 2 - device.height / 10, device.height / 2 + device.height / 6)
    //截图
    let img = null;
    while (true) {
        img = captureScreen();
        x1 = random(100, device.width - 100)
        y1 = random(device.height / 2 - device.height / 10, device.height / 2 + device.height / 6)
        if (images.detectsColor(img, "#e2d6ac", x1, y1)) {
        } else {
            break
        }
    }
    return { x1, y1 }
}





//当前是否播放完毕
function hasPlayOver() {
    playOver = false
    //播放完毕关键字
    let playOverKey = ['可领奖', '免费获取', '任务已完成']
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)
    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        for (let j = 0; j < playOverKey.length; j++) {
            let t = playOverKey[j]
            if (text.includes(t)) {
                tool.log(`播放完毕:${t}`)
                playOver = true
                break
            }
        }
        if (playOver) {
            break
        }
    }
    if (isChange()) {   //界面变化了

    } else {
        if (notChangeCount >= 3) {
            tool.log(`界面未变化:${notChangeCount}`)
            tool.log(`播放完毕`)
            playOver = true
        }
    }
    return playOver
}

//判断当前是否在广告页面
function atAdvice() {
    //是否在广告页面
    let gg = false
    if (text('反馈').exists() && text('反馈').findOne(2000).bounds().bottom < 300) {
        tool.log(`当前在video页面:存在反馈1${text('反馈').findOne(2000).bounds()}`)
        return true
    }
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)
    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        for (let j = 0; j < videoKeys.length; j++) {
            let t = videoKeys[j]
            if (text.includes(t)) {
                tool.log(`当前在video页面:存在`)
                gg = true
            }
        }
        if (gg) {
            break
        }
    }
    return gg
}

//关闭广告
function closeAD() {
    try {
        //当前不在广告页面
        if (!atAdvice()) {
            return false
        }
        if (tool.hasText('任务已完成')) {
            tool.log('关闭video:任务已完成')
            click((56 + 168) / 2, (182 + 294) / 2)
            return true
        }
        if (tool.hasText('跳过')) {
            tool.log('关闭video:跳过')
            // tool.clickhasTextByScreenCapture('跳过')
            click(1051, (198 + 264) / 2)
            return true
        }
        if (closePop()) {
            tool.log('关闭video:文字弹窗')
            return true
        }
        if (closePop2()) {
            tool.log('关闭video:图标弹窗')
            return true
        }
        let ids = ['noah_hc_close_button', 'ksad_end_close_btn']
        for (let i = 0; i < ids.length; i++) {
            let p = idContains(ids[i]).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                tool.log(`关闭广告:`)
                return true
            }
        }
        return false
    } catch (e) {
        return false
    }
}

//关闭广告播放中的弹窗
function closePlayAdviceDialog() {
    //广告页面
    if (text('继续观看').exists()) {
        click('继续观看')
        return true
    }
    let flag = false
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)
    //弹窗图标关键字
    let close = ['盲盒', '秒后得', '后续播', '应用详情', '后过期', '福袋', '刮刮乐']
    //弹窗文字关键字
    let close2 = ['不用了', '继续观看', '返回', '残忍离开', '坚持离开', '取消', '拒绝', '已下载', '跳过']
    //长按关键字
    let close3 = ['提前', '快进', '长按']

    //上划关键字
    let up = ['秒后得']

    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        for (let j = 0; j < close.length; j++) {
            let t = close[j]
            if (text.includes(t)) {
                tool.log(`存在关闭图标关键字:${t}`)
                closePop2()
                flag = true
            }
        }
        for (let j = 0; j < close2.length; j++) {
            let t = close2[j]
            if (text.includes(t)) {
                if (t === '跳过') {
                    tool.log(`存在关闭文字关键字0:${t}`)
                    click(res[i]['bounds'].centerX() + 30, res[i]['bounds'].centerY())
                } else if (t === '继续观看') {
                    tool.log(`存在关闭文字关键字1:${t}`)
                    tool.clickTextByScreenCapture(t)
                    flag = true
                } else {
                    tool.log(`存在关闭文字关键字2:${t}`)
                    tool.clickhasTextByScreenCapture(t)
                    flag = true
                }
            }
        }

        for (let j = 0; j < close3.length; j++) {
            let t = close3[j]
            if (text.includes(t)) {
                tool.log(`存在长时间按键关键字:${t}`)
                press(700, 1000, 3000)
                flag = true
            }
        }

        for (let j = 0; j < up.length; j++) {
            let t = up[j]
            if (text.includes(t)) {
                tool.log(`存在上划关键字:`)
                swipe(700, 1000, 700, 500, 1000)
                flag = true
            }
        }
    }
    closePop2()    //关闭弹窗
    return flag
}


//是否在主页面
function checkRunPage() {
    let f = 0
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)

    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        for (let j = 0; j < home.length; j++) {
            if (text.includes(home[j])) {
                f = f + 1
            }
        }
    }
    if (f >= 2) {
        notHomeCount = 0
        return true
    } else {
        notHomeCount++
        tool.log(`不在主页面:${notHomeCount}`)
        launchApp('幸福庄园')
        return false
    }
}


//检查是否需要重启
function checkRestartApp() {
    closePop2()
    isChange()
    if (notHomeCount >= 5) {
        notHomeCount = 0
        restartApp()
    }
    if (notChangeCount > maxNotChangeCount) {
        tool.log(`界面未变化${maxNotChangeCount}次,重启应用`)
        restartApp()
    }
}

//重启应用
function restartApp() {
    tool.restartApp('幸福庄园')
    sleep(3000)
    tool.clickTextByScreenCapture('跳过')
    sleep(3000)
    closePop2()
}

//关闭弹窗
function closePop() {
    let img = captureScreen();
    let res = gmlkit.ocr(img, "zh");
    res = tool.convertTextToArray(res.children)
    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        for (let j = 0; j < hasOpenCloseDialog.length; j++) {
            let t = hasOpenCloseDialog[j]
            if (text.includes(t)) {
                if (t === '当前猫舍等级') {
                    click(device.width / 2, device.height / 3 * 2)
                } else {
                    tool.clickTextByScreenCapture(t)
                }
                return true
            }
        }
    }
    return false
}



//关闭弹窗图标
function closePop2() {
    //是否找到弹窗
    let isFindPop = false
    let p = null;
    try {
        let base = captureScreen();
        let closesImage = ['close.png', 'close1.png', 'close2.png', 'close3.png', 'close4.png', 'close5.png', 'close6.png', 'close7.png']
        // let closesImage = ['close3.png']
        for (let i = 0; i < closesImage.length; i++) {
            let template = closesImage[i]
            template = images.read(`./image/${template}`);
            p = images.findImage(base, template, {
                "threshold": 0.7,
            })
            if (p !== null) {
                tool.log(`关闭弹窗${closesImage[i]},${p.x}:${p.y}`)
                // press(p.x, p.y, 200);
                press(p.x + 40, p.y + 20, 200);
                return true
            } else {
                // console.log(`未找到弹窗${closesImage[i]}`)
            }
        }
    } catch (e) {
        tool.log(`找图异常:${e}`);
    }
    return isFindPop
}
// exports.main = main
tool.init()
main()
// closePop2()